<?php


namespace app\app\controller;


use app\admin\model\Config;
use EasyWeChat\Factory;
use think\Controller;
use think\Db;


//todo 如果不需要微信登录直接继承 Controller

class Business extends UserBase
{
    protected $businessInfo;
    protected $businessID;

    protected function initialize()
    {
        parent::initialize();
        $token = $_SERVER['HTTP_TOKEN'] ?? '';
        if (empty($token)) {
            responseJson(-100, '请先登录服务站端');
        }
        //todo 使用明文openid 后面加密 解密
        $business = Db::name('business')->where('token', '=', $token)->find();
        if (!$business) {
            responseJson(-100, '服务站登录信息有误');
        }
        $this->businessInfo = $business;
        $this->businessID = $business['id'];
    }

    //通过商品id返回商品信息
    public function getGoodsByIdVB($id)
    {
        return Db::name('goods')->find($id);
    }

    public function getBusinessInfo()
    {
        $data = $this->businessInfo;
        $data['avr_url'] = $this->memberInfo['avatarUrl'];
        msg(0, '查询成功', $data);
    }

    /**
     * 首页订单状态数量
     */
    public function indexOrder()
    {
        //'0待支付 1待发货 2待收货 配送中 3已完成 4已取消 5售后',
        $timescope = getTimestampScope(-1);
        $where[] = ['business_id', '=', $this->businessID];
        $where2[] = ['create_time', 'between', [$timescope[0], $timescope[1]]];
        $data = array(
            'amount' => array(
                'total' => Db::name('order')->where($where)->where('status', 3)->sum('price'),
                'yesterday' => Db::name('order')->where($where)->where($where2)
                    ->where('status', 3)
                    ->sum('price'),
            ),
            'order' => array(
                'total' => Db::name('order')->where($where)->where('status', 3)->count(),
                'yesterday' => Db::name('order')->where($where)->where($where2)->where('status', 3)->count(),
            ),
            'handle' => array(
                'total' => Db::name('order')->where($where)->where('status', 1)->count(),
                'yesterday' => Db::name('order')->where($where)->where($where2)->where('status', 1)->count(),
            ),

            'de_pay' => Db::name('order')->where($where)->where('status', 0)->count(),

            'de_delive' => Db::name('order')->where($where)->where('status', 1)->count(),

            'after' => Db::name('order')->where($where)->where('status', 5)->count(),
        );
//        $data = array(
//            'amount' => array(
//                'total' => 200,
//                'yesterday' => 100,
//            ),
//            'order' => array(
//                'total' => 200,
//                'yesterday' => 100,
//            ),
//            'handle' => array(
//                'total' => 200,
//                'yesterday' => 100,
//            ),
//            'de_pay' => 200,
//
//            'de_delive' => 289,
//
//            'after' => 300,
//        );
        msg(0, '查询完成', $data);
    }

    /**
     * todo 先写固定数据
     * 服务站端首页饼状图
     */
    public function indexChart()
    {
        //todo 更改格式
        $data = $this->request->param();
        $type = $data['type'];
        //1 2 3 昨天 7天 30天
        switch ($type) {
            case 1:
                $timescope = getTimestampScope(-1);
                break;
            case 2:
                $timescope = getTimestampScope(-7);
                break;
            case 3:
                $timescope = getTimestampScope(-30);
                break;
            default:
                $timescope = getTimestampScope(-1);
        }
        $where2[] = ['o.create_time', 'between', [$timescope[0], time()]];
        //status 0待支付 1待发货 2待收货 配送中 3已完成 4已取消 5售后
        //订单完成
        $name = [];
        $value = [];
        $goods_cate = Db::name('goods_categoty')->where('is_del', 0)->select();
        foreach ($goods_cate as $k => $v) {
            $goods_ids = Db::name('goods')
                ->where('cate_id', $v['id'])
                ->column('id');
            $goods_num = Db::name('order_detail')->alias('od')
                ->where('od.goods_id', 'in', $goods_ids)
                ->where('o.business_id', $this->businessID)
                ->where($where2)
                ->leftJoin('order o', 'od.order_id=o.id')
                ->sum('od.goods_num');
            $return_data[] = ['value' => $goods_num, 'name' => $v['name']];
//            $name[] = $v['name'];
//            $value[] = $goods_num;
//            $data[] = ['value' => $goods_num, 'name' => $v['name']];
        }
//        $return_data = array(
//            $name, $value
//        );
//        $return_data = array(
//            [
//                '大桶水', '瓶装水', '一次性大桶水', 'other'
//            ],
//            [
//                50, 60, 42, 60
//            ],
//        );
        msg(0, '查询完成', $return_data);
    }

    /**
     * 服务站首页售后管理订单列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function afterOrderList()
    {
//       前端 1.待处理 2已处理
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['o.business_id', '=', $this->businessID];
        if ($data['status'] == 1) {
            $where[] = ['oa.status', '=', $data['status']];
        } else {
            $where[] = ['oa.status', '<>', 1];
        }
        //todo 售后订单搜索暂时不处理
        if ($data['search']) {
            $where[] = ['o.search', 'like', '%' . $data['search'] . '%'];
        }
        $return_data = Db::name('order')
            ->alias('o')
            ->field('o.id,o.order_no,o.price,o.create_time,oa.id as oa_id,oa.member_remark,oa.create_time as oa_create_time')
            ->join('order_after oa', 'o.id=oa.order_id')
            ->order('oa.create_time desc')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                //todo 单商品下单只要一个商品信息
                $order_detail = Db::name('order_detail')->where('order_id', $item['id'])->find();
                $item['goods'] = Db::name('goods')->field('id,name,specs,img')->find($order_detail['goods_id']);
                return $item;
            });
        msg(0, '查询成功', $return_data);
    }

    //服务站订单
    public function orderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['business_id', '=', $this->businessID];
        //0全部 '1待支付 2待发货 3配送中 4已完成  5已取消 6售后 前端返回
        if ($data['status']) {
            $where[] = ['status', '=', $data['status'] - 1]; //'0待支付 1待发货 2配送中 3已完成  4已取消 5售后
        }
        $return_data = Db::name('order')
            ->order('create_time desc')
            ->where($where)
            ->where('status', '<>', 0) //0809 服务站显示订单列表不显示未支付
            ->paginate([
                $length, false, [
                    'page' => $page
                ]
            ])->each(function ($item) {
                $item['address_info'] = Db::name('delivery_address')->find($item['address_id']);
                $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
                $item['order_detail'] = Db::name('order_detail')->where('order_id', '=', $item['id'])->find();
                $item['goods_detail'] = Db::name('goods')->find($item['order_detail']['goods_id']);
                if ($item['delivery_id']) {
                    $item['delivery_info'] = Db::name('delivery')->find($item['delivery_id']);
                }
                return $item;
            });
        msg(0, '查询成功', $return_data);
    }

    public function financeList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['business_id', '=', $this->businessID];
        //1.推广 2线上销售 3进货 4提现
        if ($data['type']) {
            $where[] = ['type', '=', $data['type']];
        }
        $data_list = Db::name('business_finance')->where($where)->paginate([
            $length, false, [
                'page' => $page
            ]
        ])->each(function ($item) {
            $item['create_time'] = date('Y-m-d H:i', $item['create_time']);
            return $item;
        });
        $return_data['data_list'] = $data_list;
        //账户余额
        $return_data['amount'] = $this->businessInfo['amount'];
        //累计提现
        $tixianCount = Db::name('business_finance')
            ->where(['type' => 4, 'status' => 1, 'business_id' => $this->businessID])
            ->sum('amount');
        $return_data['tixianCount'] = $tixianCount;
        msg(0, '查询成功', $return_data);
    }

    //订单配送列表
    public function deliveryOrderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        // 1待发货  服务站待发货的订单
        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['status', '=', 1];
        $where[] = ['pay_status', '=', 1];
        $order_list = Db::name('order')
            ->order('create_time desc')
            ->where($where)
            ->paginate([$length, false, [
                'page' => $page
            ]])->each(function ($item) {
                $item['address'] = Db::name('delivery_address')->find($item['address_id']);
                $item['business_info'] = $this->businessInfo;
                $order_detail = Db::name('order_detail')->where('order_id', $item['id'])->find();
                $item['order_detail'] = $order_detail;
                $item['goods_detail'] = Db::name('goods')->find($order_detail['goods_id']);
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    public function deliveryOrderDetail()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_list = Db::name('order')->find($order_id);
        $order_list['address'] = Db::name('delivery_address')->find($order_list['address_id']);
        $order_list['business_info'] = $this->businessInfo;
        msg(0, '查询成功', $order_list);
    }

    //指定派送列表
    public function getDelivery()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['status', '=', 1];
        $where[] = ['is_del', '<>', 1];
        $data_list = Db::name('delivery')->where($where)->paginate([
            $length, false, [
                'page' => $page
            ]
        ])->each(function ($item) {
            $item['water_station'] = $this->businessInfo;
            return $item;
        });
        msg(0, '查询完成', $data_list);
    }

    //派单
    public function dispatch()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        Db::startTrans();
        try {
            $update_date = array(
                'id' => $order_id,
                'status' => 2,
                'dispatch_time' => time(),
                'delivery_role' => $data['delivery_role']
            );
            if ($data['delivery_role'] == 2) {//1 服务站配送 2员工配送
                $update_date['delivery_id'] = $data['delivery_id'];
            }
            $update_order = Db::name('order')->update($update_date);
            Db::commit();
            msg(0, '查询成功', $update_order);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
        msg(-1, '当前员工不可排单', '1');
    }

    /**
     * 创建员工
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function createDelivery()
    {
        $data = $this->request->param();
        $create_time = time();
        $insert_data = array(
            'name' => $data['name'],
            'username' => $data['username'],
            'password' => md5($data['password'] . 'delivery'),
            'pass' => $data['password'],
            'phone' => $data['phone'],
            'create_time' => $create_time,
            'status' => 1,
            'business_id' => $this->businessID,
            'salt' => md5($create_time . $data['password']),
            'count' => 0,
            'no' => $create_time . $this->getNO()
        );
        $where2[] = ['is_del', '=', 0];
        $info = Db::name('delivery')
            ->where($where2)
            ->where(['username' => $data['username']])->find();
        if ($info) {
            msg(-1, '账号已存在，请更改账号', '');
        }
        Db::startTrans();
        try {
            $business_id = Db::name('delivery')->insertGetId($insert_data);
            Db::commit();
            msg(0, '增加成功', $business_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取员工列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getEmployList()
    {
        $where[] = ['is_del', '<>', 1];
        $dataList = Db::name('delivery')
            ->where(['business_id' => $this->businessID])
            ->where($where)
            ->order('create_time desc')
            ->select();
        foreach ($dataList as $k => $v) {
            $dataList[$k]['password'] = $v['pass'];
        }
        msg(0, '查询成功', $dataList);
    }

    /**
     * 服务站创建订单
     */
    public function businessPurchase()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $goods_list = $this->getCartTong();
            if (!$goods_list) {
                msg(-1, '购物车为空', '');
            }
            $balance = $data['balance'];
            $cash = $data['cash'];
            $pay_type = 3; //'支付方式 1余额支付 2直接支付 3混合支付'
            if ($balance == 0) {
                $pay_type = 2;
            }
            if ($cash == 0) {
                $pay_type = 1;
            }
            $business_order = array(
                'order_no' => GetOrderSN(2) . $this->businessID,
                'business_id' => $this->businessID,
                'status' => 0,//'0待支付 1待发货 2已完成'
                'create_time' => time(),
                'pay_status' => 0,
                'balance' => $balance,
                'cash' => $cash,
                'pay_type' => $pay_type,
            );
            $bo_id = Db::name('business_order')->insertGetId($business_order);
            $price = 0;
            foreach ($goods_list as $k => $v) {
                $goods_mgs = $this->getGoodsByIdVB($v['goods_id']);
                if (!$goods_mgs) {
                    msg(-1, '商品不存在', '');
                }
                $bod_data = array(
                    'business_order_id' => $bo_id,
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $goods_mgs['name'],
                    'goods_price' => $goods_mgs['purchase_price'],
                    'goods_num' => $v['num'],
                    'subtotal' => $goods_mgs['purchase_price'] * $v['num']
                );
                Db::name('business_order_detail')->insertGetId($bod_data);
                $price += $goods_mgs['purchase_price'] * $v['num'];
            }
            //todo 删除购物车
            Db::name('business_order_car')->where('business_id', $this->businessID)->delete();
            $update = array(
                'id' => $bo_id,
                'price' => $price
            );
            Db::name('business_order')->update($update);
            $order_info = Db::name('business_order')->find($bo_id);
            Db::commit();
            msg(0, '新增成功', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 服务站创建订单
     */
    public function businessPurchase2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $pay_type = $data['pay_type'];  //'支付方式 1余额支付 2直接支付 3混合支付'
            $goods_list = $this->getCartTong();
            if (!$goods_list) {
                msg(-1, '购物车为空', '');
            }
            $price = 0;
            foreach ($goods_list as $k => $v) {
                $goods_mgs = $this->getGoodsByIdVB($v['goods_id']);
                if ($goods_mgs['is_water'] == 1) {
                    $ca_where[] = ['is_del', '=', 0];
                    $ca_where[] = ['is_kong', '=', 1];
                    $kong_info = Db::name('goods')
                        ->where($ca_where)
                        ->find();
                    $ca2_where[] = ['business_id', '=', $this->businessID];
                    $ca2_where[] = ['goods_id', '=', $kong_info['id']];
                    $kong_car = Db::name('business_order_car')->where($ca2_where)->find();
                    if ($kong_car) {
                        if ($kong_car['num'] != $v['num']) {
                            msg(-1, '请添加相等数量空桶', '');
                        }
                    } else {
                        msg(-1, '请添加相等数量空桶', '');
                    }
                }
                if (!$goods_mgs) {
                    msg(-1, '商品不存在', '');
                }
                $price += $goods_mgs['purchase_price'] * $v['num'];
            }
            $business_order = array(
                'order_no' => GetOrderSN(2),
                'business_id' => $this->businessID,
                'status' => 0,//'0待支付 1待发货 2已完成'
                'create_time' => time(),
                'pay_status' => 0,
                'price' => $price,
                'pay_type' => $pay_type,

            );
            if ($pay_type == 1) {
                if ($this->businessInfo['amount'] >= $price) {
                    $business_order['balance'] = $price;
                    $business_order['cash'] = 0;
                } else {
                    msg(-1, '余额不足', '');
                }
            } else if ($pay_type == 3) {
                $business_order['balance'] = $this->businessInfo['amount'];
                $business_order['cash'] = $price - $this->businessInfo['amount'];
            } else {//默认 直接支付
                $business_order['balance'] = 0;
                $business_order['cash'] = $price;
            }
            $bo_id = Db::name('business_order')->insertGetId($business_order);
            $business_order['id'] = $bo_id;
            foreach ($goods_list as $k => $v) {
                $goods_mgs = $this->getGoodsByIdVB($v['goods_id']);
                $bod_data = array(
                    'business_order_id' => $bo_id,
                    'goods_id' => $v['goods_id'],
                    'goods_name' => $goods_mgs['name'],
                    'goods_price' => $goods_mgs['purchase_price'],
                    'goods_num' => $v['num'],
                    'dai_num' => $v['num'],
                    'subtotal' => $goods_mgs['purchase_price'] * $v['num']
                );
                Db::name('business_order_detail')->insertGetId($bod_data);
            }
            //todo 删除购物车
            Db::name('business_order_car')->where('business_id', $this->businessID)->delete();
            Db::commit();
            msg(0, '新增成功', $business_order);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //服务站订单列表 todo 增加未支付订单显示前端
    public function businessOrderList()
    {
        //前端发送 0 全部 1待付款 2待收货 3已完成
        //后台           0待支付 1待发货 2已完成 3待收货 配送中
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['is_del', '=', 0];
        //轮播支付订单
        $all_order_nopay = Db::name('business_order')
            ->where('pay_status', '=', 0)
            ->page($page, $length)
            ->select();
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        foreach ($all_order_nopay as $k => $v) {
            $res = $app->order->queryByOutTradeNumber($v['order_no']);
            if ($res['trade_state'] == "SUCCESS") {
                $this->BusinessOrderPayed($v['id']);
            }
        }
        $status = input('status/d', 0);
        //'0待支付 1待发货 2已完成' 3配送中
        if (isset($data['status'])) {
            $where[] = ['status', '=', $data['status']];
        }
        $order_list = Db::name('business_order')
            ->where($where)
            ->order('create_time desc')
            ->paginate([
                $length, false, [
                    'page' => $page
                ]
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i');
                $item['order_detail'] = Db::name('business_order_detail')
                    ->alias('bod')
                    ->join('goods g', 'g.id=bod.goods_id')
                    ->field('bod.*,g.name,g.specs,g.img')
                    ->where('bod.business_order_id', '=', $item['id'])
                    ->select();
                return $item;
            });
        msg(0, '查询完成', $order_list);
    }

    /**
     * 服务站订单支付
     * 余额支付
     */
    public function payOrderByBalance()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $business_order_info = Db::name('business_order')->find($order_id);
        if ($business_order_info['price'] > $this->businessInfo['amount']) {
            msg(-1, '余额不足', $this->businessInfo['amount']);
        }
        $this->BusinessOrderPayed($order_id);
        msg(0, '支付完成', 1);
    }

    /**
     * 确认服务站订单收货
     */
    public function setBusinessOrderStatus()
    {
        $data = $this->request->param();
        $where[] = ['id', '=', $data['id']];
        //'0待支付 1待发货 2已完成',
        $update_data = array(
            'get_goods_time' => time(),
            'status' => 2
        );
        Db::startTrans();
        try {
            $update_id = Db::name('business_order')
                ->where($where)
                ->update($update_data);
            Db::commit();
            msg(0, '收货成功', $update_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }
    //数据分析
    //今日交易数量 确定已经支付的 不管什么支付类型  退款数量
    //交易数已经支付订单 退款数已经退款订单
    public function getBusinessData1()
    {
        $timestamp = strtotime("today midnight");
        $yday = getTimestamp(-1);

        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['pay_status', '=', 1];

        //今日交易额
        $today_pay_sum = Db::name('order')
            ->where($where)
            ->where('pay_time', 'between', [$timestamp, time()])
            ->sum('price');
        //本月交易笔数
        $today_pay_count = Db::name('order')
            ->where($where)
            ->where('pay_time', 'between', [$timestamp, time()])->count();
        //本月收益金额
        $today_tui_count = Db::name('order')
            ->where($where)
            ->where('pay_time', 'between', [$timestamp, time()])
            ->sum('price');


        $yday_pay = Db::name('order')
            ->where($where)
            ->where('pay_time', 'between', [$yday[0], $yday[1]]);
        //昨日交易额
        $yday_pay_sum = $yday_pay->sum('price');
        //昨日交易笔数
        $yday_pay_count = $yday_pay->count();
        //昨日退款数量
        $yday_tui_count = $yday_pay->where('is_tui', '=', 2)->count();
        //今日交易额上涨率
        $price_rate = $yday_pay_sum == 0 ? 0 : ($today_pay_sum - $yday_pay_sum) / $yday_pay_sum * 100;
        //交易笔数上涨率
        $count_rate = $yday_pay_count == 0 ? 0 : ($today_pay_count - $yday_pay_count) / $yday_pay_count * 100;
        //退款笔数上涨率
        $tui_count_rate = $yday_tui_count == 0 ? 0 : ($today_tui_count - $yday_tui_count) / $yday_tui_count * 100;
        $data['today_pay_sum'] = $today_pay_sum; //今日交易额
        $data['today_pay_count'] = $today_pay_count;   //今日交易笔数
        $data['today_tui_count'] = $today_tui_count;  //今日退款数量
        $data['price_rate'] = $price_rate;//今日交易额上涨率
        $data['count_rate'] = $count_rate;//交易笔数上涨率
        $data['tui_count_rate'] = $tui_count_rate; //退款笔数上涨率
        msg(0, '查询成功', $data);
    }

    //todo 切换真数据 先固定数据
    public function getBusinessData2()
    {
// 昨日
//        $yesterdayStart = strtotime("yesterday");
//        $yesterdayEnd = strtotime("tomorrow") - 1;
//
// 上周
//        $lastWeekStart = strtotime("last week");
//        $lastWeekEnd = strtotime("this week") - 1;
//
// 上月
//        $lastMonthStart = strtotime("last month");
//        $lastMonthEnd = strtotime("next month") - 1;
        $data = $this->request->param();
        $type = input('type/d', 1);
        switch ($type) {
            case 1:
                $startTimestamp = strtotime("today");
                $y_d[] = strtotime("yesterday");
                $y_d[] = strtotime("tomorrow") - 1;
                break;
            case 2:
                $startTimestamp = strtotime("this week Monday");
                $y_d[] = strtotime("last week");
                $y_d[] = strtotime("this week") - 1;
                break;
            case 3:
                $startTimestamp = strtotime("first day of this month");
                $y_d[] = strtotime("last month");
                $y_d[] = strtotime("next month") - 1;
                break;
        }
        $order_base = Db::name('order')->where('business_id', $this->businessID)->where('status', 3);

        $price1 = $order_base->where('create_time', 'between', [$startTimestamp, time()])
            ->sum('price');
        $price2 = $order_base->where('create_time', 'between', [$y_d[0], $y_d[1]])
            ->sum('price');
        if ($price2) {
            $price_add = ($price1 - $price2) / $price2;
        } else {
            $price_add = 0;
        }
        $count1 = $order_base->where('create_time', 'between', [$startTimestamp, time()])
            ->count();
        $count2 = $order_base->where('create_time', 'between', [$y_d[0], $y_d[1]])
            ->count();
        if ($count2) {
            $count_add = ($count1 - $count2) / $count2;
        } else {
            $count_add = 0;
        }
        $return_data = array(
            'price_count' => $price1,
            'price_count_rate' => $price_add,
            'order_count' => $count1,
            'order_count_rate' => $count_add
        );
        msg(0, '查询成功', $return_data);
    }

    //todo 切换真数据 先固定数据
    public function getBusinessData3()
    {
        $daysAgo = [];
        $price = [];
        $where[] = ['status', '=', 2];
        for ($i = 5; $i >= 1; $i--) {
            $daysAgo[] = date('d日', strtotime(-$i . " days"));
            $timescope = getTimestamp(-$i);
            $where[] = ['create_time', 'between', [$timescope[0], $timescope[1]]];
            $price[] = Db::name('order')->where($where)->sum('price');
        }
//        $data[] = $daysAgo;
//        $data[] = $price;
        $return_data = array($daysAgo, $price);
        msg(0, '', $return_data);

//        $return_data = array(
//            [
//                8, 9, 10, 11, 12
//            ],
//            [
//                22345.12, 32345.12, 42345.12, 52345.12, 62345.12,
//            ],
//        );
//        msg(0, '查询成功', $return_data);
    }

    //用户订单排名
    public function getBusinessData4()
    {
        //以用户订单id 为组合
        $where[] = ['o.business_id', '=', $this->businessID];
        $where[] = ['o.pay_status', '=', 1];
        $data = Db::name('order')
            ->alias('o')
            ->join('member me', 'o.member_id=me.id')
            ->group('o.member_id')
            ->order('order_num desc')
            ->where($where)
            ->field('o.member_id,count(*) as order_num,me.nickname,me.avatarUrl,me.mobile')
            ->limit(5)
            ->select();
        foreach ($data as $k => $v) {
            if (!strpos($v['avatarUrl'], 'ttp')) {
                $data[$k]['avatarUrl'] = config('wechat.url') . $v['avatarUrl'];
            }
        }

        msg(0, '', $data);
    }

    //服务站提现接口
    public function BusinessTixian()
    {
        $data = $this->request->param();
        $businessInfo = $this->businessInfo;
        if ($data['amount'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['amount'] > $businessInfo['amount']) {
            msg(-1, '提现金额不能大于余额', '');
        }
        Db::startTrans();
        try {
            $insert_data = array(
                'business_id' => $this->businessID,
                'amount' => $data['amount'],
                'tixian_type' => $data['tixian_type'], //提现类型 1微信 2支付宝 3银行
                'tixian_account' => $data['tixian_account'], //提现账号
                'tixian_name' => $data['tixian_name'],//提现人姓名
                'tixian_bank' => $data['tixian_bank'],//提现银行名（银行提现使用）
                'status' => 0,//'0未完成 待审核 1已完成 审核完成 提现使用',
                'type' => 4,
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_id = Db::name('business_finance')->insertGetId($insert_data);
            Db::name('business')
                ->where('id', '=', $this->businessID)
                ->setDec('amount', $data['amount']);
            Db::commit();
            msg(0, '更新成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //删除配送员
    public function delDelivery()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['id'],
            'is_del' => 1
        );
        $count = Db::name('delivery')->update($update);
        msg(0, '更新成功', $count);
    }

    /**
     * 通过详细地址获取经纬度
     */
    public function getNO($length = 6)
    {
        $randomNumber = '';
        for ($i = 0; $i < $length; $i++) {
            $randomNumber .= mt_rand(0, 9); // 每次迭代生成一个0-9之间的随机数字并拼接到结果字符串中
        }
        return $randomNumber;
    }

    //获取服务站购物车 通用
    public function getCartTong()
    {
        $data = Db::name('business_order_car')->alias('boc')
            ->field('boc.*,goods.img,goods.name,goods.purchase_price,goods.specs,goods.is_kong,goods.is_water')
            ->join('goods', 'boc.goods_id=goods.id')
            ->where('business_id', $this->businessID)
            ->order('create_time desc')
            ->select();
        foreach ($data as $k => $v) {
            if ($v['is_kong'] == 1) {
                $data[$k]['is_tt2'] = '空桶';
            }
            if ($v['is_water'] == 1) {
                $data[$k]['is_tt'] = '大桶水';
            }
        }
        return $data;
    }

    //获取服务站购物车
    public function getCar()
    {
        $data = $this->getCartTong();
        msg(0, '查询成功', $data);
    }


    //增加商品
    public function addCart()
    {
        $data = $this->request->param();
        $goods_id = $data['goods_id'];
        $num = $data['num'];
        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['goods_id', '=', $goods_id];
        $car_goods = Db::name('business_order_car')->where($where)->find();
        Db::startTrans();
        try {
            if ($car_goods) {
                Db::name('business_order_car')->where($where)->setInc('num', $num);
            } else {
                $insert_data = array(
                    'goods_id' => $goods_id,
                    'num' => $num,
                    'business_id' => $this->businessID,
                    'create_time' => time()
                );
                Db::name('business_order_car')->insertGetId($insert_data);
            }
            $data = Db::name('business_order_car')->alias('boc')
                ->field('boc.*,goods.img,goods.name,goods.purchase_price,goods.specs')
                ->join('goods', 'boc.goods_id=goods.id')
                ->where('business_id', $this->businessID)
                ->order('create_time desc')
                ->select();
            Db::commit();
            msg(0, '操作成功', $data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //减少商品
    public function delCart()
    {
        $data = $this->request->param();
        $goods_id = $data['goods_id'];
        $num = $data['num'];
        $where[] = ['business_id', '=', $this->businessID];
        $where[] = ['goods_id', '=', $goods_id];
        $car_goods = Db::name('business_order_car')->where($where)->find();
        if (!$car_goods) {
            msg(-1, '操作有误', '');
        }
        if ($car_goods['num'] < $num) {
            msg(-1, '操作有误', '');
        }
        Db::startTrans();
        try {
            if ($car_goods['num'] == $num) {
                Db::name('business_order_car')->where($where)->delete();
            } else {
                Db::name('business_order_car')->where($where)->setDec('num', $num);
            }
            $data = Db::name('business_order_car')->alias('boc')
                ->field('boc.*,goods.img,goods.name,goods.purchase_price,goods.specs')
                ->join('goods', 'boc.goods_id=goods.id')
                ->where('business_id', $this->businessID)
                ->order('create_time desc')
                ->select();
            Db::commit();
            msg(0, '操作成功', $data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //清空购物车
    public function cleatCar()
    {
        $where[] = ['business_id', '=', $this->businessID];
        Db::name('business_order_car')->where($where)->delete();
        msg(0, '查询成功', '');
    }

    //服务站上下线
    public function operationStatus()
    {
        //1 上线 0 下线 operation_status
        $data = $this->request->param();
        $update = array(
            'id' => $this->businessID,
            'operation_status' => $data['operation_status']
        );
        Db::name('business')->update($update);
        msg(0, '更改成功', $data['operation_status']);
    }

    /**
     * 配送人员点击送达
     */
    public function deliverOrder()
    {
        $data = $this->request->param();
        //经纬度
        $order_id = $data['order_id'];
        $latitude = $data['latitude'];
        $longitude = $data['longitude'];
        //判断是否在附近
        $order_info = Db::name('order')->find($order_id);
        $address = Db::name('delivery_address')->find($order_info['address_id']);
        $from = $latitude . ',' . $longitude;
        $to = $from . ';' . $address['latitude'] . ',' . $address['longitude'];
        $distance = getDistance($from, $to);
        //todo 距离先固定以后在后台可设置 已完成默认1000
        $allow_distance = config('site.deliver_distance') ? config('site.deliver_distance') : 1000;
        if ($distance > $allow_distance) {
            msg(-1, '距离过远，请靠近确认', '');
        }
        $result = deliverGo($order_id, 1, 1, $this->businessID);
        if ($result == -1) {
            msg(-1, '操作有误', $result);
        }
        msg(0, '更新完成', $result);
    }

    //订单扫码核销
    public function verifyOrder()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $result = deliverGo($order_id, 2, 1, $this->businessID);
        if ($result == -1) {
            msg(-1, '操作有误', $result);
        }
        msg(0, '更新完成', $result);
    }
    //商家四位核销码核销
    //write_code_digits
    public function verifyOrderDigits()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $write_code_digits = $data['write_code_digits'];
        $result = deliverGo($order_id, 3, 1, $this->businessID, '', $write_code_digits);
        if ($result == -1) {
            msg(-1, '操作有误', $result);
        }
        msg(0, '更新完成', $result);
    }

    //服务站确认收货
    public function confirmGoods()
    {
        //todo
        $data = $this->request->param();
        $business_order_id = $data['business_order_id'];
        $order_detail_id = $data['order_detail_id'];
        $remark = $data['remark'];
        if (isset($data['confirm_num'])) {
            $confirm_num = $data['confirm_num'];
        } else {
            $detail_info = Db::name('business_order_detail')
                ->find($order_detail_id);
            $confirm_num = $detail_info['to_num'];
        }
        if (!$business_order_id || !$order_detail_id) {
            msg(-1, '缺少数据', '');
        }
        Db::startTrans();
        try {
            $update_time = array(
                'id' => $order_detail_id,
                'business_confirm' => 1,
                'confirm_num' => $confirm_num,
                'confirm_time' => time(),
                'remark' => $remark
            );
            Db::name('business_order_detail')->update($update_time);
            $this->isAllget($business_order_id);
            Db::commit();
            msg(0, '更新成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //本次订单是否完成全部收货
    public function isAllget($business_order_id)
    {
        $order_info = Db::name('business_order_detail')
            ->where('business_order_id', $business_order_id)
            ->select();
        $is_all = true;
        if ($order_info) {
            foreach ($order_info as $k => $v) {
                if ($v['business_confirm'] == 0) {
                    $is_all = false;
                }
            }
            if ($is_all) {
                Db::name('business_order')->update(
                    array(
                        'id' => $business_order_id,
                        'status' => 2,
                        'get_goods_time' => time()
                    )
                );
            }
        }
    }

    //订单完成条件 时间 pay——time 订单已支付状态
    //获取当月
    public function getBusinessInvoiceList()
    {
        $data = $this->request->param();
        $year = $data['year'];
//        $month=$data['month'];
        if (isset($year) && (date('Y') != $year)) {
            $startOfYear = strtotime("$year-01-01 00:00:00");
            $startOfYear2 = strtotime("$year-12-31 23:59:59");
            $months_list = getAllMonths($startOfYear, $startOfYear2);
        } else {
            $year1 = date('Y'); // 获取当前年份
            $startOfYear = strtotime("$year1-01-01 00:00:00");
            if ($this->businessInfo['create_time'] > $startOfYear) {
                $months_list = getAllMonths($this->businessInfo['create_time'], time());
            } else {
                $months_list = getAllMonths($startOfYear, time());
            }
        }
        $data = array();
        $kai_num = 0;
        $weikai_num = 0;

        $months_list = array_reverse($months_list);
        $data_list = array();
        foreach ($months_list as $k => $v) {
            $dataScope = explode('--', $v);
            $dataScope = getMonthTimestampRange($dataScope[0], $dataScope[1]);
            $data_list[$k]['id'] = $k + 1;
            $data_list[$k]['date'] = $v;
            //订单数量
            $order_count = Db::name('business_order')
                ->where('pay_time', 'between', [$dataScope[0], $dataScope[1]])
                ->where('business_id', '=', $this->businessID)
                ->where('porder_id', '=', 0)
                ->count();
            //订单总金额
            $amount_count = Db::name('business_order')
                ->where('pay_time', 'between', [$dataScope[0], $dataScope[1]])
                ->where('business_id', '=', $this->businessID)
                ->where('porder_id', '=', 0)
                ->sum('price');
            $data_list[$k]['order_num'] = $order_count;
            $data_list[$k]['amount_count'] = $amount_count;
            $data_list[$k]['is_kai'] = 0;
            $bc_info = Db::name('business_order_invoice')
                ->where('business_id', '=', $this->businessID)
                ->where('date', '=', $v)
                ->find();
            if ($bc_info) {
                $data_list[$k]['is_kai'] = 1;
                $kai_num++;
            }else{
                $weikai_num++;
            }
        }
        $data['kai_num'] = $kai_num;
        $data['weikai_num'] = $weikai_num;
        $data['data_list'] = $data_list;
        msg(0, '查询成功', $data);
    }

    public function invoiceOrderDetail()
    {
        $data = $this->request->param();
        $dataScope = explode('--', $data['date']);
        $dataScope = getMonthTimestampRange($dataScope[0], $dataScope[1]);
        $_list = Db::name('goods')
            ->order(array('id' => 'desc'))
            ->where('is_del', '=', 0)
            ->select();
        $order_where[] = ['business_id', '=', $this->businessID];
        $order_where[] = ['pay_status', '=', 1];
        $order_where[] = ['porder_id', '=', 0];
        $order_where[] = ['pay_time', 'between', [$dataScope[0], $dataScope[1]]];
        $order_ids = Db::name('business_order')
            ->where($order_where)
            ->column('id');
        $order_detail_where[] = ['business_order_id', 'in', $order_ids];
        foreach ($_list as $k => $v) {
            //总销量
            $count_sum = Db::name('business_order_detail')
                ->where('goods_id', $v['id'])
                ->where($order_detail_where)
                ->sum('goods_num');
            //总价格
            $subtotal_sum = Db::name('business_order_detail')
                ->where('goods_id', $v['id'])
                ->where($order_detail_where)
                ->sum('subtotal');
            $_list[$k]['subtotal_sum'] = $subtotal_sum;
            $_list[$k]['count_sum'] = $count_sum;
            $_list[$k]['goods_price'] = $v['purchase_price'];
        }
        msg(0, '查询成功', $_list);
    }

    public function openInvoice()
    {
        $data = $this->request->param();
        $dataScope = explode('--', $data['date']);
        $dataScope = getMonthTimestampRange($dataScope[0], $dataScope[1]);
        $invoice_info=Db::name('business_order_invoice')
            ->where('business_id','=',$this->businessID)
            ->where('date','=',$data['date'])
            ->find();
        if ($invoice_info){
            msg(-1,'发票已创建，请勿重复提交', '');
        }
        //订单总金额
        $amount_count = Db::name('business_order')
            ->where('pay_time', 'between', [$dataScope[0], $dataScope[1]])
            ->where('business_id', '=', $this->businessID)
            ->where('porder_id', '=', 0)
            ->sum('price');
//        if($amount_count==0){
//            msg(-1,'金额为0，无法开票', '');
//        }
        Db::startTrans();
        try {
            $insert_data=array(
                'business_id'=>$this->businessID,
                'create_time'=>time(),
                'count_amount'=>$amount_count,
                'date'=>$data['date'],
                'yingye_name'=>$this->businessInfo['yingye_name'],
                'bank_name'=>$this->businessInfo['bank_name'],
                'bank_no'=>$this->businessInfo['bank_no'],
                'yingye_address'=>$this->businessInfo['yingye_address'],
                'receive_email'=>$this->businessInfo['receive_email'],
            );
            Db::name('business_order_invoice')->insertGetId($insert_data);
            Db::commit();
            msg(0, '增加成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }
}